/*axios中文说明文档*/
//https://www.kancloud.cn/yunye/axios/234845

import { isJSON } from './tool';

import { Loading } from 'element-ui';

import axios from 'axios';

import Vue from 'vue';

import { refreshToken } from '../api/api';

Vue.prototype.$axios = axios;

// axios.defaults.baseURL = serverurl;

/*请求超时时间*/
axios.defaults.timeout = 60000;

/* `url` 是用于请求的服务器 URL*/
// axios.defaults.url = '/api'

/*
* // 用于请求之前对请求数据进行操作
  // 只用当请求方法为‘PUT’，‘POST’和‘PATCH’时可用
  // 最后一个函数需return出相应数据
  // 可以修改headers
  */
// axios.defaults.transformRequest = function(data,headers){
//     console.log("请求的参数")
//     console.log(JSON.stringify(data));
//     console.log(qs.stringify(data));
//     console.log(typeof data)
//     console.log(typeof JSON.stringify(data))
//     return qs.stringify(data);
// }

//`transformResponse` 在传递给 then/catch 前，允许修改响应数据
axios.defaults.transformResponse = function (data) {
	// console.log(data);
	// console.log(typeof data)
	if (isJSON(data)) {
		return JSON.parse(data);
	}
	return data;
};

// `withCredentials` 表示跨域请求时是否需要使用凭证 默认false
axios.defaults.withCredentials = false;

/*定义允许的响应内容的最大尺寸*/
axios.defaults.maxContentLength = 20000;

/*request拦截器*/
axios.interceptors.request.use(
	function (res) {
		return res;
	},
	function (error) {
		Loading.service({ fullscreen: true }).close();
		return Promise.reject(error);
	}
);

let isRefreshing = false; // 标记是否正在刷新token
let requests = []; // 存储待重发请求的数组

/*response拦截器*/
axios.interceptors.response.use(
	resp => {
		console.log('response interceptors', resp);
		return resp;
	},
	error => {
		console.log('response interceptors error', error, error.response);
		//判断是否是token过期了
		if (error.response && error.response.status === 401 && error.response.data && error.response.data.code === '1101' && error.response.config?.url.indexOf('/ivcs/api/v1/auth/refresh-token')!== -1) {
			let body = {
				userId: localStorage.getItem(`zco_admin_userId_${window.uid}`),
				ticket: localStorage.getItem(`zco_admin_ticket_${window.uid}`)
			};
			const { config } = error.response;
			if (!isRefreshing) {
				isRefreshing = true;
				return refreshToken(body)
					.then(resp => {
						console.log('refresh token success', resp);
						let token = resp.data.accessToken;
						localStorage.setItem(`zco_admin_ticket_${window.uid}`, resp.data.ticket);
						localStorage.setItem(`zco_admin_token_${window.uid}`, token);
						localStorage.setItem(`zco_admin_ticket`, resp.data.ticket);
						localStorage.setItem(`zco_admin_token`, token);
						error.response.config.headers['x-access-token'] = token;
						requests.forEach(cb => cb(token));
						requests = [];
						return axios.request(error.response.config);
					})
					.catch(e => {
						console.log('refersh ticket error', e, e.response);
						return Promise.reject(e);
					})
					.finally((error) => {
						console.log('refersh ticket finally error', error);
						isRefreshing = false;
					});
			}
			return new Promise(resolve => {
				requests.push(token => {
					config.headers['x-access-token'] = token;
					resolve(axios.request(config));
				});
			});
		} else if (error.code === 'ECONNABORTED') {
			return Promise.reject(error);
		}
		let err = error.response?.data || error.response || error;
		return Promise.reject(err);
	}
);
/** 设置 token 请求头 */
axios.interceptors.request.use(
	function (config) {
		/** 用户是否传入 token */
		let token = window.localStorage.getItem(`zco_admin_token_${window.uid}`);
		if (!config.headers['x-access-token'] && token) {
			config.headers['x-access-token'] = token;
		}
		/** 用户是否传入 Content-Type */
		if (!config.headers['Content-Type']) {
			config.headers['Content-Type'] = 'application/json';
		}
		return config;
	},
	function (error) {
		return Promise.reject(error);
	}
);

export default axios;
